﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Spotless.Data;
using System.Web.Mvc;
using System.Web.Routing;

namespace SpotlessWeb.ViewHelpers
{
    public static class ViewDataHelpers
    {
        public static void AddCategories(this ViewDataDictionary source, List<Category> categories)
        {
            source["Categories"] = categories;
        }

        public static List<Category> GetCategories(this ViewDataDictionary source)
        {
            return source["Categories"] as List<Category>;
        }

        public static List<SelectListItem> GetCategoriesAsSelectList(this ViewDataDictionary source)
        {
            var cats = source.GetCategories();
            return cats.Select(x => new SelectListItem
                    {
                        Text = x.Name,
                        Value = x.CategoryId.ToString()
                    }).ToList();
        }

        public static RouteValueDictionary GetAllExistingRouteValues(this ViewContext viewContext)
        {
            var queryString = viewContext.RequestContext.HttpContext.Request.QueryString;
            RouteValueDictionary tmp = viewContext.RouteData.Values;
            foreach (string key in queryString.Keys)
            {
                string val = queryString[key];
                if (val.Contains(","))
                {
                    var values = val.Split(',');
                    for (var i = 0; i < values.Length; i++)
                    {
                        tmp.Add(key + "[" + i + "]", values[i]);
                    }
                }
                else
                {
                    tmp.Add(key, val);
                }
            }
            return tmp;
        }
    }
}
